package co.yixiang.mall.biz.commission.service.impl;

import co.yixiang.mall.biz.commission.mapper.CommissionService;
import co.yixiang.mall.biz.commission.mapper.StoreService;
import co.yixiang.mall.biz.commission.mapper.ShopService;
import co.yixiang.mall.biz.commission.mapper.ShopTypeService;
import co.yixiang.mall.biz.entity.SysRetailType;
import co.yixiang.mall.biz.util.OrderTypeUtil;
import co.yixiang.mall.common.shop.domain.YxSystemStore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Log4j2
public class CommissionServiceImpl implements co.yixiang.mall.biz.commission.service.CommissionService {

    @Autowired
    CommissionService commissionService;

    @Autowired
    ShopService shopService;

    @Autowired
    ShopTypeService shopTypeMapper;

    @Autowired
    StoreService storeService;

    @Override
    public void SettlementSet(){
        YxSystemStore systemStore = new YxSystemStore();
        systemStore.setSettleAccounts(0);
        shopService.update(systemStore,new QueryWrapper<YxSystemStore>().eq("settle_accounts", 1));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer serviceCharge(){
        /** 查询所有店铺开始结算 */
        QueryWrapper wrapper = new QueryWrapper();
        List<YxSystemStore> shop = shopService.selectList(null);
        shop.forEach(sh->{
            /** 查询今日该店铺服务费是否结算完毕 */
            if(sh.getSettleAccounts()==0){
                /** 查询中心店和社区店的比例 */
                SysRetailType sysRetailType1 = shopTypeMapper.selectById(2);
                /** 查询店铺属于中心店还是社区店 */
                SysRetailType sysRetailType = shopTypeMapper.selectById(sh.getRetailType());
                /** 获得店铺服务费比例 */
                if(sysRetailType.getId()==0||sysRetailType.getId()==1){
                    BigDecimal fuwu = OrderTypeUtil.Centre(sh,sysRetailType.getService(), commissionService,sysRetailType1,storeService);
                    /** 将服务费添加进用户余额 */
                    sh.setStoreMoney(sh.getStoreMoney().add(fuwu));
                    sh.setSettleAccounts(1);
                    shopService.updateById(sh);
                }else{
                    log.error("门店类型异常");
                }
            }
        });
        return 1;
    }
}
